<!--
  * 首页 用户头部信息
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-09-12 22:34:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
  *
-->
<template>
  <div class="user-header">
    <!-- <a-button type="primary" @click="exportWord">导出</a-button> -->
    <a-page-header :title="welcomeSentence">
      <template #subTitle>
        <span style="color: #666; margin-left: 20px">所属部门：{{ departmentName }} </span>
      </template>
      <template #extra>
        <p style="color: #333">{{ dayInfo }}</p>
      </template>
      <a-row class="content">
        <span class="left-content">
          <p class="last-login-info">
            <AlertOutlined />{{ lastLoginInfo }}
          </p>
          <a class="sentence" href="#" target="_blank"> <smile-outlined spin /> {{ heartSentence }} </a>
        </span>
        <div class="weather">
          <iframe width="100%" scrolling="no" height="50" frameborder="0" allowtransparency="true"
            src="//i.tianqi.com/index.php?c=code&id=12&icon=1&num=3&site=12"></iframe>
        </div>
      </a-row>
    </a-page-header>

  </div>
</template>
<script setup>
import { computed, ref } from 'vue';
import { useUserStore } from '/@/store/modules/system/user';
import uaparser from 'ua-parser-js';
import { Solar, Lunar } from 'lunar-javascript';
import _ from 'lodash';
import heartSentenceArray from './heart-sentence';
import { message } from 'ant-design-vue';

import PizZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
import JSZip from 'jszip';

const userStore = useUserStore();

const departmentName = computed(() => userStore.departmentName);


const detailAll = ref(
  [
    {
      registerSchool: "测试学校1",
      jobCode: '老师',
      actualName: '张三1',
      gender: '男'
    },
    {
      registerSchool: "测试学校2",
      jobCode: '老师',
      actualName: '张三2',
      gender: '男'
    },
  ]

)

// 图片压缩前转换
function imgToBuffer(url) {
  return new Promise((resolve, reject) => {
    const xml = new XMLHttpRequest();
    xml.open('GET', url, true);
    xml.responseType = 'blob';
    xml.onload = function ({ currentTarget }) { //从事件对象结构出currentTarget
      const { status, response } = currentTarget;
      status === 200 ? resolve(response) : reject(status); // response就是转化后的
    };
    xml.send();
  });
}

function imgToBuffer2(response) {
  return new Promise((resolve, reject) => {
    resolve(response)
  });
}
// 开始压缩
function uploadData() {
  const zip = new JSZip();
  const imgCache = {};
  const imgArr = [];
  let list = [
    { name: '测试图片1', url: 'https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF' },
    { name: '测试图片2', url: 'https://t7.baidu.com/it/u=727460147,2222092211&fm=193&f=GIF' },
    { name: '测试图片3', url: 'https://t7.baidu.com/it/u=3911840071,2534614245&fm=193&f=GIF' },
    { name: '测试图片4', url: 'https://t7.baidu.com/it/u=938052523,709452322&fm=193&f=GIF' },
  ];
  list.forEach((item) => { // urlList格式：[{url:图片链接,name:图片名称}...]
    // 逐个添加文件
    const promise = imgToBuffer(item.url).then((res) => {
      zip.file(`${item.name}.${res.type.split('/').pop()}`, res, { binary: true });
      imgCache[item.name] = res; // 下载文件, 并存成ArrayBuffer对象(blob)
      console.log(imgCache);
    });
    console.log(promise);


    imgArr.push(promise);
    console.log(imgArr);


  });


  Promise.all(imgArr).then(() => {
    zip.generateAsync({ type: 'blob' }).then((content) => {
      console.log(content);
      // saveAs(content, '压缩包名称'); // 打包压缩
      // this.$message.success('压缩完成');
    }).catch((err) => {
      this.$message.error(err.message);
    });
  });
}


const exportWord = async () => {
  console.log('Starting exportWord function...');
  const zip2 = new JSZip();
  let resArr=[]
  // 读取并获得模板文件的二进制内容
  //这里填本地线下地址位置是public里的entryForm.docx文件
  for (let i = 0; i < detailAll.value.length; i++) {
    const content = await fetchTemplate("public/test.docx");
    //这里是可以填线上文档的地址
    // const content = await fetchTemplate("https://media/1719454190427-668.docx");
    console.log('-----', content);
    // 创建一个JSZip实例，内容为模板的内容
    let zip = new PizZip(content);
    console.log('+++++', zip);
    // 创建并加载docxtemplater实例对象
    let doc = new Docxtemplater();
    console.log('/', doc);
    doc.loadZip(zip);
    console.log('=====', doc);
    // 设置模板变量的值（把里层对象也放置第一层好使用）
    doc.setData({
      ...detailAll.value[i]
    });
    console.log('设置模板变量的值', doc);
    try {
      // 用模板变量的值替换所有模板变量
      doc.render();
    } catch (error) {
      // 抛出异常
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      };
      console.log(JSON.stringify({ error: e }));
      throw error;
    }
   

    // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
    let out = doc.getZip().generate({
      type: 'blob',
      mimeType:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });

    //saveAs((out), '111');

    console.log(out);
    const promise = imgToBuffer2(out).then((res) => {
    })
    zip2.file(detailAll.value[i].actualName+'.docx', out);
    resArr.push(promise)
  }

  Promise.all(resArr).then(async () => {
    const zipContent = await zip2.generateAsync({ type: "blob" })
    console.log(zipContent);

    saveAs((zipContent), '老师信息表'); // 打包压缩
    message.success('压缩完成');
  }).catch((err) => {
    message.error(err.message);
  });
  // saveAs(out, '员工信息.docx');
};
const fetchTemplate = (templateUrl) => {
  return new Promise((resolve, reject) => {
    JSZipUtils.getBinaryContent(templateUrl, (error, content) => {
      if (error) {
        reject(error);
      } else {
        resolve(content);
      }
    });
  });
};


// 欢迎语
const welcomeSentence = computed(() => {
  let sentence = '';
  let now = new Date().getHours();
  if (now > 0 && now <= 6) {
    sentence = '午夜好，';
  } else if (now > 6 && now <= 11) {
    sentence = '早上好，';
  } else if (now > 11 && now <= 14) {
    sentence = '中午好，';
  } else if (now > 14 && now <= 18) {
    sentence = '下午好，';
  } else {
    sentence = '晚上好，';
  }
  return sentence + userStore.$state.actualName;
});

//上次登录信息
const lastLoginInfo = computed(() => {
  let info = '';
  if (userStore.$state.lastLoginTime) {
    info = info + '上次登录:' + userStore.$state.lastLoginTime;
  }

  if (userStore.$state.lastLoginUserAgent) {
    let ua = uaparser(userStore.$state.lastLoginUserAgent);
    info = info + '; 设备:';
    if (ua.browser.name) {
      info = info + ' ' + ua.browser.name;
    }
    if (ua.os.name) {
      info = info + ' ' + ua.os.name;
    }
    let device = ua.device.vendor ? ua.device.vendor + ua.device.model : null;
    if (device) {
      info = info + ' ' + device + ';';
    }
  }

  if (userStore.$state.lastLoginIpRegion) {
    info = info + '; ' + userStore.$state.lastLoginIpRegion;
  }
  if (userStore.$state.lastLoginIp) {
    info = info + '; ' + userStore.$state.lastLoginIp;
  }
  return info;
});

//日期、节日、节气
const dayInfo = computed(() => {
  //阳历
  let solar = Solar.fromDate(new Date());
  let day = solar.toString();
  let week = solar.getWeekInChinese();
  //阴历
  let lunar = Lunar.fromDate(new Date());
  let lunarMonth = lunar.getMonthInChinese();
  let lunarDay = lunar.getDayInChinese();
  //节气
  let jieqi = lunar.getPrevJieQi().getName();
  let next = lunar.getNextJieQi();
  let nextJieqi = next.getName() + ' ' + next.getSolar().toYmd();

  return `${day} 星期${week}，农历${lunarMonth}${lunarDay}（当前${jieqi}，${nextJieqi} ）`;
});

// 毒鸡汤
const heartSentence = computed(() => {
  return heartSentenceArray[_.random(0, heartSentenceArray.length - 1)];
});
</script>
<style scoped lang="less">
.user-header {
  width: 100%;
  background-color: #fff;
  margin-bottom: 10px;

  .left-content {
    width: calc(100% - 420px);

    h3 {
      color: rgba(0, 0, 0, 0.75);
    }
  }

  .content {
    display: flex;
    justify-content: space-between;

    .weather {
      width: 400px;
    }
  }

  .last-login-info {
    font-size: 13px;
    color: #333;
    overflow-wrap: break-word;
    padding: 0;
    margin: 1px 0 0 0;
  }

  .sentence {
    display: block;
    font-size: 12px;
    color: #acacac;
    overflow-wrap: break-word;
    padding: 5px 0 0 0;
    margin: 6px 0 0 0;
  }

  .sentence:hover {
    cursor: pointer;
    text-decoration: underline;
  }
}
</style>
